import { getVideoCameraListV3 } from '@/api/camera'
import {
    addCommonPointLayer,
    addImageToMap,
    pointIsInHangzhou,
    removeLayerAndSource,
    removeMarkers,
} from './common-map-tools'
import { layerMap } from './layer-id'
import { getMapImagePath } from '@/config/map-image-config'

// 渲染摄像头普通图层
export const controlCameraVideoCommonPointLayer = async (
    options: { codes: string; type: string; onClickPoint?: (e: any) => void } | null,
) => {
    const layerId = layerMap.cameraVideoCommonPointLayer
    if (options && options.codes && options.type) {
        // 移除图层
        removeLayerAndSource(layerId)
        // 获取远程数据
        const { data } = await getVideoCameraListV3({
            cameraType: options.codes,
            type: options.type,
            isRepeat: true,
            reservedNum: 2,
        })
        // 构建geojson
        const listData = data?.list ?? []
        const dynamicImages: any = {}
        const geojson = {
            type: 'FeatureCollection',
            features: listData
                .filter((item: any) => {
                    if (item.lon >= 180 || item.lon <= -180) {
                        return false
                    }
                    if (item.lat >= 90 || item.lat <= -90) {
                        return false
                    }
                    if (!item.lon || !item.lat) {
                        return false
                    }
                    return pointIsInHangzhou([item.lon, item.lat])
                })
                .sort((a: any, b: any) => {
                    return b.lon - a.lon
                })
                .map((item: any) => {
                    const imageName = `camera-${item.status}`
                    const imagePath = getMapImagePath(imageName)
                    if (imagePath) {
                        dynamicImages[imageName] = imagePath
                    }
                    return {
                        type: 'Feature',
                        geometry: {
                            type: 'Point',
                            coordinates: [item.lon, item.lat],
                        },
                        properties: {
                            ...item,
                            imageName,
                            type: options.type,
                        },
                    }
                }),
        }
        // 添加收集需添加的地图上的点位图片
        await addImageToMap(
            Object.keys(dynamicImages).map(key => {
                return {
                    imageName: key,
                    imagePath: dynamicImages[key],
                }
            }),
        )
        // 添加图层
        addCommonPointLayer({
            layerId,
            layerOptions: {
                type: 'symbol',
                layout: {
                    'icon-image': '{imageName}',
                    'icon-size': 0.65,
                    'icon-ignore-placement': true,
                },
            },
            geojson,
            onClick: (e: any) => {
                options.onClickPoint && options.onClickPoint({ ...e.features[0].properties })
            },
            hoverTipField: 'cameraName',
        })
        // 添加重复点位图层
        controlCameraVideoRepeatPointLayer({
            data: data?.repeat ?? [],
            type: options.type,
            onClickPoint: options.onClickPoint,
        })
    } else {
        removeLayerAndSource(layerId)
        controlCameraVideoRepeatPointLayer(null)
    }
}

// 渲染摄像头重复点位图层
let repetNumMarkers: any = []
export const controlCameraVideoRepeatPointLayer = async (
    options: { data: any[]; type: any; onClickPoint?: (e: any) => void } | null,
) => {
    const layerId = layerMap.cameraVideoRepeatPointLayer
    if (options && options.data && options.data.length) {
        // 移除图层
        removeLayerAndSource(layerId)
        removeMarkers(repetNumMarkers)
        repetNumMarkers = []

        // 构建geojson
        const listData = options.data
        const dynamicImages: any = {}
        const geojson = {
            type: 'FeatureCollection',
            features: listData
                .filter((item: any) => {
                    if (item.lon >= 180 || item.lon <= -180) {
                        return false
                    }
                    if (item.lat >= 90 || item.lat <= -90) {
                        return false
                    }
                    if (!item.lon || !item.lat) {
                        return false
                    }
                    return pointIsInHangzhou([item.lon, item.lat])
                })
                .sort((a: any, b: any) => {
                    return b.lon - a.lon
                })
                .map((item: any) => {
                    const imageName = `camera-${item.status}`
                    const imagePath = getMapImagePath(`camera-${item.status}`)
                    if (imagePath) {
                        dynamicImages[imageName] = imagePath
                    }

                    const el = document.createElement('div')
                    el.innerHTML = `<div style="text-align:center;">
                        <div style="position: relative;">
                            <div style="width: ${item.num > 100 ? '24px' : '20px'};height: 20px;line-height: 20px;font-size: 12px;font-weight: 700;color: #FFF;text-align: center;position: absolute;left: 16px;transform: translateX(-50%);top: -26px;background: #0084FF;border-radius: 3px;border:1px solid #FFF">${item.num}</div>
                        </div>
                    </div>`
                    repetNumMarkers.push(
                        new window.mapboxgl.Marker({
                            element: el,
                        }).setLngLat([item.lon, item.lat]),
                    )

                    return {
                        type: 'Feature',
                        geometry: {
                            type: 'Point',
                            coordinates: [item.lon, item.lat],
                        },
                        properties: {
                            ...item,
                            imageName,
                            type: options.type,
                            isRepeat: true,
                        },
                    }
                }),
        }
        // 添加收集需添加的地图上的点位图片
        await addImageToMap(
            Object.keys(dynamicImages).map(key => {
                return {
                    imageName: key,
                    imagePath: dynamicImages[key],
                }
            }),
        )
        // 添加图层
        addCommonPointLayer({
            layerId,
            layerOptions: {
                type: 'symbol',
                layout: {
                    'icon-image': '{imageName}',
                    'icon-size': 0.65,
                    'icon-ignore-placement': true,
                },
            },
            geojson,
            onClick: (e: any) => {
                options.onClickPoint && options.onClickPoint({ ...e.features[0].properties })
            },
            hoverTipField: '',
        })
        setTimeout(() => {
            repetNumMarkers.forEach((marker: any) => {
                marker.addTo(window.glMap)
            })
        }, 500)
    } else {
        removeMarkers(repetNumMarkers)
        removeLayerAndSource(layerId)
        repetNumMarkers = []
    }
}
